<?php

namespace wxapp\aes;

class sign {
    private $key;  //AppSecret
    private $iv;   //app_secret 取前16位
    private $type;  //AppSecret

    /**
     * 构造函数
     * @param $sessionKey string 用户在小程序登录后获取的会话密钥
     * @param $appid string 小程序的appid
     */
    public function __construct($key, $iv) {
        $this->key     = $key;
        $this->iv      = $iv;
        $this->type    = 'AES-128-CBC';
    }

    /**
     * 接口加密操作
     * @param $str 需要加密的字串
     * @param $key AppSecret
     * @param $iv app_secret 取前16位
     * @return string 加密后字串
     */
    public function wx_encrypt($str) {
        $key = $this->key;
        $iv  = $this->iv;
        $str = $str . str_repeat("\0", 16 - strlen($str) % 16);
        $encrypt = openssl_encrypt($str, $this->type, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);

        return bin2hex($encrypt);
    }

    /** 
     * 解密操作
     * @param $str 解密字串
     * @param $key AppSecret
     * @param $iv app_secret 取前16位
     * @return string 解密后字串
     */
    public function wx_decrypt($str) {
        $key = $this->key;
        $iv  = $this->iv;
        $decrypt = openssl_decrypt(hex2bin($str), $this->type, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
        return rtrim($decrypt, "\0");
    }

}

